package com.bookbuf.social.share.content.media.image.converter;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Build;

import com.bookbuf.social.secure.AesHelper;
import com.bookbuf.social.share.content.media.image.util.Util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class ResConverter extends ConfiguredConverter {

	private Context context;
	private int resId = 0;

	public ResConverter (Context context, int b) {
		this.context = context;
		this.resId = b;
	}

	@Override
	public File asFile () {

		File file = null;
		FileOutputStream outputStream = null;
		FileInputStream inputStream = null;

		try {
			AssetFileDescriptor descriptor = this.context.getResources ().openRawResourceFd (this.resId);
			inputStream = descriptor.createInputStream ();
			file = getConfig ().generateCacheFile (AesHelper.md5 (inputStream.toString ()));
			outputStream = new FileOutputStream (file);
			byte[] buffer = new byte[4096];

			while (inputStream.read (buffer) != -1) {
				outputStream.write (buffer);
			}

			outputStream.flush ();
			return file;
		} catch (IOException e) {
			e.printStackTrace ();
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close ();
				}

				if (outputStream != null) {
					outputStream.close ();
				}
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}
		return null;
	}

	@Override
	public String asUrl () {
		return null;
	}

	@Override
	public byte[] asBinary () {

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
		Resources resources = this.context.getResources ();
		Drawable drawable;
		if (Build.VERSION.SDK_INT >= 21) {
			drawable = resources.getDrawable (this.resId, (Resources.Theme) null);
		} else {
			drawable = resources.getDrawable (this.resId);
		}

		Bitmap bitmap = Util.createBitmap (drawable);
		bitmap.compress (Bitmap.CompressFormat.PNG, 100, outputStream);
		return outputStream.toByteArray ();
	}

	@Override
	public Bitmap asBitmap () {
		return BitmapFactory.decodeResource (this.context.getResources (), this.resId);
	}
}